package api

import (
	"github.com/gin-gonic/gin"
	"log"
	"oidc/model"
	"oidc/service"
	"oidc/util"
	"time"
)

func IfTokenTimeOut() gin.HandlerFunc {
	return func(c *gin.Context) {
		aToken := c.PostForm(util.GetCode(util.ACCESS_TOKEN))
		//idToken := c.Query(util.GetCode(util.ID_TOKEN))

		var aTokenClaim = service.AccessTokenClaims{}

		accToken, err := aTokenClaim.ParserToken(aToken)
		if err != nil {
			log.Println(err)
			c.JSON(401, gin.H{
				"status": false,
				"data":   "ParserToken err",
			})
			c.Abort()
			return
		}
		if accToken.ExpiresAt < time.Now().Unix() {
			log.Println("A token time out")
			c.JSON(401, gin.H{
				"status": false,
				"data":   "Token time out",
			})
			c.Abort()
			return
		}

		c.Next()
		log.Println("Token success")
	}
}

func QueryEndPoint() gin.HandlerFunc {
	return func(c *gin.Context) {
		//aToken := c.Query(util.GetCode(util.ACCESS_TOKEN))
		idToken := c.PostForm(util.GetCode(util.ID_TOKEN))

		var idClaim = service.IdTokenClaims{}

		IToken, err := idClaim.ParserIdToken(idToken)

		if err != nil {
			log.Println(err)
			c.JSON(401, gin.H{
				"status": false,
				"data":   "ParserIDToken err",
			})
			c.Abort()
			return
		}
		if IToken.ExpiresAt < time.Now().Unix() {
			log.Println("A token time out")
			c.JSON(401, gin.H{
				"status": false,
				"data":   "Token time out",
			})
			c.Abort()
			return
		}

		userInfo := model.UserInfo{
			Identifier: IToken.Uid,
			UserName:   IToken.UserNames,
			Email:      IToken.Email,
			Phone:      IToken.Phone,
		}

		c.JSON(200, userInfo)

	}
}
